package com.wzqj.agent.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.common.Log;
import com.wzqj.agent.common.Page;
import com.wzqj.agent.common.constant.WebConstant;
import com.wzqj.agent.web.domain.Agent;
import com.wzqj.agent.web.domain.Detail;
import com.wzqj.agent.web.domain.Sales;
import com.wzqj.agent.web.domain.User;
import com.wzqj.agent.web.service.AgentService;
import com.wzqj.agent.web.service.DetailService;
import com.wzqj.agent.web.service.SalesService;
import com.wzqj.agent.web.service.UserService;
import com.wzqj.web.http.CookieUtils;
import com.wzqj.wsp.config.Config;

@Controller
@RequestMapping("/sales")
public class SalesWebController {

	private Logger log = LogManager.getLogger(SalesWebController.class);
	
	@Autowired
	private UserService userService;
	@Autowired
	private SalesService salesService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private DetailService detailService;
	/**
	 * 业务员列表
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/salesList")
	public String salesList(@RequestParam(value = "pageNo", defaultValue = "1")  Integer pageNo,
			HttpServletRequest request){
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				return "/user/admin/login";
			}
			Integer userId = Integer.parseInt(userToken);
			//获取用户信息
			User user  = userService.getById(userId);
			request.setAttribute("user", user);
			//获取用户 下的代理商信息
			Page<Sales> saleses = salesService.getByUserPage(userId,pageNo);
			if (saleses!=null) {
				log.info("saleses："+saleses);
				request.setAttribute("saleses", saleses);
				
			}
			
			Integer roleId = user.getRoleId();
			if (WebConstant.roleID_admin==roleId) {
				/*Agent agentSelf = agentService.getById(user.getTypeId());
				request.setAttribute("agentSelf", agentSelf);*/
			}
			if (WebConstant.roleID_agent_level1==roleId) {
				Agent agentSelf = agentService.getById(user.getTypeId());
				request.setAttribute("agentSelf", agentSelf);
			}
			if (WebConstant.roleID_agent_level2==roleId) {
				Agent agentSelf = agentService.getById(user.getTypeId());
				request.setAttribute("agentSelf", agentSelf);
			}
			rv="/user/agent/salesmanManagement";
			
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return rv;
	}
	
	@RequestMapping("/toInsert")
	public String toInsert(Integer parentId,ModelMap map,HttpServletRequest request){
		Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return "redirect:user/index.xhtml";
		}
		Integer userId = Integer.parseInt(userToken);
		User user = userService.getById(userId);
		map.put("user", user);
		map.put("parentId", parentId);
		return "/user/agent/salesmanAdd";
	}
	/**
	 * 新增业务员
	 * @param name
	 * @param phone
	 * @param job
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping("/insert")
	@ResponseBody
	public JSONObject insert(Integer parentId,String name,String phone,String job,HttpServletRequest request,ModelMap map){
		JSONObject data = new JSONObject();
		try {
			User isExit = userService.getByUsername(phone);
			if (isExit!=null) {
				data.put("status", 0);
				data.put("info", "该手机号已存在！");
				return data;
			}
			//新建业务员
			Sales sales =  new Sales();
			sales.setName(name);
			sales.setPhone(phone);
			sales.setJob(job);
			sales.setStatus(WebConstant.status_normal);
			sales.setParentId(parentId);
			int newSalesId = salesService.insert(sales);
			if (newSalesId==0) {
				data.put("status", 0);
				data.put("info", "新增业务员失败！");
				return data;
			}
			//Sales newSales = salesService.getById(newSalesId);
			//新建业务员账户
			User user = new User();
			user.setUsername(phone);
			user.setPassword(phone);
			user.setRoleId(WebConstant.roleID_sales);
			user.setType(WebConstant.user_type_sales);
			user.setTypeId(newSalesId);
			user.setStatus(WebConstant.status_freeze);//第一期先将业务员账号冻结
			userService.insert(user);
			
			Detail detail = new Detail();
			detail.setSalesId(newSalesId);
			detail.setSalesPhone(phone);
			detail.setOperation(WebConstant.add_sales_operation);
			detail.setStatus(WebConstant.status_success);
			detailService.insert(detail);
			
			data.put("status", 1);
			data.put("info", "新增业务员成功！");
			
		} catch (Exception e) {
			data.put("status", 0);
			data.put("info", "新增业务员失败！");
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return data;
	}
	
	/**
	 * 跳转到代理商修改页面
	 * @param map
	 * @param agentId
	 * @return
	 */
	@RequestMapping("/toEdit")
	public String toEdit(ModelMap map,Integer salesId,HttpServletRequest request){
		Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return "redirect:user/index.xhtml";
		}
		Integer userId = Integer.parseInt(userToken);
		Sales sales = salesService.getById(salesId);
		map.addAttribute("sales", sales);
		return "/user/agent/salesmanEdit";
	}
	/**
	 * 修改业务员
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public JSONObject edit(Integer salesId,String name,String phone,String job,
			ModelMap map,HttpSession session,HttpServletRequest request){
		JSONObject data = new JSONObject();
		try {
			
			//修改业务员
			Sales sales = salesService.getById(salesId);
			if (!StringUtils.isEmpty(name)) {
				sales.setName(name);
			}
			Sales isExit = salesService.getByPhone(phone);
			if (isExit==null) {
				data.put("status",0);
				data.put("info", "该手机号已经存在！");
				return data;
			}
			if (!StringUtils.isEmpty(phone)) {
				sales.setPhone(phone);
			}
			if (!StringUtils.isEmpty(job)) {
				sales.setJob(job);
			}
			
			salesService.update(sales);
			
			data.put("status", 1);
			data.put("info", "修改业务员成功！");
			data.put("data", sales);
		} catch (Exception e) {
			data.put("status",0);
			data.put("info", "修改业务员失败！");
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return data;
	}
	/**
	 * 冻结/解冻代理商的账户
	 * @param agentId
	 * @param userStatus
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/freeze")
	public JSONObject freeze(Integer salesId,Integer status,
			ModelMap map,HttpServletRequest request ){
		JSONObject data = new JSONObject();
		//查询代理商
		try {
			/*User user = userService.getByType(2, salesId);
			user.setStatus(status);//
			userService.update(user);//冻结/解冻
			*/			
			Sales sale = salesService.getById(salesId);
			sale.setStatus(status);
			salesService.update(sale);
			
			data.put("status", 1);
	
			if (status==WebConstant.status_freeze) {
				data.put("info", "冻结成功！");
			}
			if (status==WebConstant.status_normal) {
				data.put("info", "解冻成功！");
			}
			
		} catch (Exception e) {
			data.put("status",0);
			if (status==WebConstant.status_freeze) {
				data.put("info", "冻结失败！");
			}
			if (status==WebConstant.status_normal) {
				data.put("info", "解冻失败！");
			}
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return data;
	}
	
}

	